package morning.cat.springbootdemo.controller;

import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping(value = "/api/v1.0")
@Api(value = "用户管理开放API 版本1.0")
public class FileController {


    @GetMapping("/test1")
    public void test1(HttpServletResponse response) throws IOException {

        ResponseEntity<byte[]> entity = null;
        OutputStream outputStream = null;
        try {
            String fileName = "文件名.txt";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);


            String content = "文件内容：\r\n你好狗子";
            byte[] data = content.getBytes("GBK");
            //response.setContentType("application/octet-stream;charset=GBK");
            response.setHeader("content-type", "text/html;charset=GBK");
            response.setCharacterEncoding("GBK");


            outputStream = response.getOutputStream();
            IOUtils.write(data, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    @GetMapping("/test2")
    public void test2(HttpServletResponse response) throws IOException {

        ResponseEntity<byte[]> entity = null;
        OutputStream outputStream = null;
        try {
            String fileName = "文件名.txt";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            File file =new File("C:\\Users\\mengzhang6\\Downloads\\文件名 (2).txt");
//            byte[] data = FileUtils.readFileToString(file, "GBK").getBytes("GBK");
            byte[] data = FileUtils.readFileToString(file).getBytes("GBK");
            //response.setContentType("application/octet-stream;charset=GBK");
            response.setHeader("content-type", "text/html;charset=GBK");
            response.setCharacterEncoding("GBK");


            outputStream = response.getOutputStream();
            IOUtils.write(data, outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }


}
